package com.azdebugit.concurrent;
 
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.commons.lang3.time.FastDateFormat;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@FixMethodOrder(MethodSorters.JVM)
public class TestCountDownLatch {
 
    private static final FastDateFormat fdf = FastDateFormat.getInstance("yyy-MM-dd HH:mm:ss");
 
    private ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(5,
            new BasicThreadFactory.Builder().namingPattern("test-schedule-pool-%d").daemon(true).build());
 
    @Test
    public void testCountDownLatch() throws Exception {
        Date startDate = new Date();
 
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            String seconds = String.valueOf(i);
            executorService.submit(() -> {
                try {
//                    System.out.println(Integer.MAX_VALUE);
//                    System.out.println(Integer.MIN_VALUE);
                    TimeUnit.SECONDS.sleep(Integer.valueOf(seconds));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("线程[{}]正在休眠[{}s]", Thread.currentThread().getName(), seconds);
                /**将count值减1*/
                countDownLatch.countDown();
            });
        }
        /**调用await()方法的线程会被挂起，它会等待直到count值为0才继续执行*/
        countDownLatch.await();
 
        Date endDate = new Date();
        log.info("开始时间[{}],结束时间[{}],耗时[{}ms]", fdf.format(startDate), fdf.format(endDate), endDate.getTime() - startDate.getTime());
    }
}